module middleware.CheckJwt;

import std.json : JSONValue;

import archttp : HttpRequest, HttpResponse, HttpStatusCode;
import hunt.jwt.JwtToken;
import hunt.jwt.Exceptions;

import utils.RespData;
import utils.ConstValue : Const;

// import std.stdio;

// 验证token中间件
void checkToken (HttpRequest req, HttpResponse res, void delegate() next)
{
    string headerToken = req.header("Authorization");
    // writeln(headerToken);
    if (headerToken == "")
    {
        JSONValue respData = RespData.newData(401, "Token is incorrect");
        res.code(HttpStatusCode.UNAUTHORIZED).json(respData).send();
    }
    string encodedToken = headerToken[7 .. $];
    // writeln(encodedToken);
    try
    {
        bool isOk = JwtToken.verify(encodedToken, Const.jwtSecretStr);
        if (isOk)
        {
            next();
        }
        else
        {
            JSONValue respData = RespData.newData(401, "Token verification failed");
            res.code(HttpStatusCode.UNAUTHORIZED).json(respData).send();
        }
    }
    catch (ExpiredException e)
    {
        // writeln(e.msg);
        JSONValue respData = RespData.newData(401, e.msg);
        res.code(HttpStatusCode.UNAUTHORIZED).json(respData).send();
    }
    catch (VerifyException e)
    {
        // writeln(e.msg);
        JSONValue respData = RespData.newData(401, e.msg);
        res.code(HttpStatusCode.UNAUTHORIZED).json(respData).send();
    }
}
